package com.qd.p2p.web.action.borrow;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.UserCreditService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.util.HclientFileUtil;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.AdditionalFlowUploadType;
import com.qdlc.p2p.common.constant.BorrowUploadType;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.enums.EnumUploadImgType;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.UploadFileUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.AdditionalFlowUpload;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.BorrowUpload;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCredit;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;

/**
 * 借款标
 * 
 * @author ylx
 * @version 2.0
 * @date 2015年6月3日 上午11:28:06
 */
public class BorrowAction extends BaseAction<BorrowModel> implements ModelDriven<BorrowModel> {
	@Resource
	private BorrowService borrowService;
	@Resource
	private UserCreditService userCreditService;
	@Resource
	private UserIdentifyService userIdentifyService;
	
	private BorrowModel model = new BorrowModel();
	
	@Override
	public BorrowModel getModel() {
		return model;
	}
	private User user;

	/**
	 * 我要投资页/标种介绍页
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/borrow/index" ,results = { @Result(name = "index", type = "ftl", location = "/borrow/index.html")})
	public String index() throws Exception {
		request.setAttribute("borrowConfigList", Global.BORROW_CONFIG_LIST);
		request.setAttribute("interest_manage_fee", SystemConfigHelper.getDoubleValue(Nid.INVESTOR_MANAGE_FEE));
		return "index";
	}

	/**
	 * 发标页面
	 * 
	 * @return
	 * @throws Exception if has error
	 */
	@Action(value = "/borrow/detail", interceptorRefs = { @InterceptorRef("session"), @InterceptorRef("globalStack") })
	public String loan() throws Exception {
		user = getSessionUser();
		checkBorrowUser();
		String type = paramString("type");
		long borrowId = paramLong("borrowId");
		UserIdentify userIdentify = userIdentifyService.findByUserId(user.getUserId());
		BorrowModel.checkBorrowUser(userIdentify);
		model.setType(model.getBorrowType(StringUtil.isNull(type)));
		if (borrowId == 0) { // 发借款标
			borrowService.allowPublish(user, model);
		} else { // 修改借款标
			Borrow borrow = borrowService.find(borrowId);
			BorrowModel model = BorrowModel.instance(borrow);
			request.setAttribute("borrow", model);
		}
		request.setAttribute("typeStr", type);
		request.setAttribute("btype", model.getType());
		return "detail";
	}
	
	/**
	 * 发标
	 * 
	 * @return
	 * @throws Exception if has error
	 */
	@Action("/borrow/doLoan")
	public void doLoan() throws Exception {
		user = getSessionUser();
		if (user == null) {
			throw new UserException("由于您长时间没操作，请先登录", BusinessException.TYPE_JSON);
		}
		if (UserTypeUtils.isInvestor(user.getUserId())) {
			throw new UserException("当前用户为投资人不能发标", BusinessException.TYPE_JSON);
		}
		checkBorrowUser();
		model.validBorrowCode(paramString("valicode"));
		model.validBorrowStyle();
		// 验证定向标
		model.validDXB();
		// 新增奖励设置
		model.checkAward();
		List<BorrowUpload> list = new ArrayList<BorrowUpload>();
		// 获得上传图片字符串数组
		String[] picPaths = request.getParameterValues("picPath");
		if (picPaths == null) {
			throw new BorrowException("图片不能为空", BusinessException.TYPE_JSON);
		}

		for (String picPath : picPaths) {
			BorrowUpload bu = new BorrowUpload();
			bu.setPicPath(picPath);
			bu.setType(4);
			list.add(bu);
		}

		String[] thumbnailPaths = request.getParameterValues("thumbnailPicPath");
		if (null != thumbnailPaths
				&& thumbnailPaths.length > 0) {
			for (String picPath : thumbnailPaths) {
				BorrowUpload bu = new BorrowUpload();
				bu.setPicPath(picPath);
				bu.setType(BorrowUploadType.THUMBNAIL);
				list.add(bu);
			}
		}

		if (model.getBorrowTimeType() == 0) {
			model.setTimeLimit(paramInt("timeLimit"));
		} else {
			model.setTimeLimit(paramInt("dayLimit"));
		}
		borrowService.save(model, user, list);
		printWebSuccess();
	}
	
	/**
	 * 上传文件到服务器
	 * 
	 * @throws Exception
	 */
	@Action("/borrow/uploadBorrowPic")
	public void uploadBorrowPic() throws Exception {
		String path = imgUpload(EnumUploadImgType.BORROW.getValue());
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("picPath", path);
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 删除上传的图片
	 * 
	 * @throws Exception
	 */
	@Action("/borrow/deleteBorrowPic")
	public void deleteBorrowPic() throws Exception {
		String pathPic = paramString("pathPic");
		String url = UploadFileUtil.getMessage("deleteUrl");
		HclientFileUtil.deleteImg(url, pathPic);
		printWebSuccess();
	}

	/**
	 * 校验可用信用额度
	 */
	@Action("/borrow/checkAccount")
	public void checkAccount() {
		UserCredit amount = userCreditService.findByUserId(getSessionUser().getUserId());
		PrintWriter out = null;
		try {
			// 指定输出内容类型和编码
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			out = ServletActionContext.getResponse().getWriter();
			double creditUse = amount.getCreditUse();
			String borrowId = paramString("borrowId");
			if (!StringUtil.isBlank(borrowId)) {
				Borrow b = borrowService.find(Long.parseLong(borrowId));
				creditUse = BigDecimalUtil.add(b.getAccount(), creditUse);
			}
			if (amount == null || paramDouble("account") > creditUse) {
				String str = "您当前的可用信用额度为" + creditUse + "元<br/>可用信用额度不足<br/>";
				String add = " <a href='/member_borrow/borrow/addApply.html' style='color: red;'>点击申请</a><br/>";
				out.print(str+add);
			}
		} catch (Exception ex) {
			throw new BorrowException("校验可用信用额度异常", 1);
		} finally {
			out.close();
		}
	}

}
